package com.gzr.controller;

import com.gzr.pojo.Result;
import com.gzr.pojo.User;
import com.gzr.server.UserServer;
import com.gzr.utils.JwtUtil;
import com.gzr.utils.Md5Util;
import com.gzr.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ClusterOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserServer userServer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 注册用户
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") @RequestParam(name="username")String username, @Pattern(regexp = "^\\S{5,16}$") @RequestParam(name="password")String password) {

        //查询用户
        User user = userServer.findByUserName(username);
        if (user == null) {
            //没有占用
            //注册用户
            userServer.register(username,password);
            return Result.success();
        }else {
            return Result.error("用户名已被占用");
        }
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") @RequestParam(name="username") String username, @Pattern(regexp = "^\\S{5,16}$") @RequestParam(name="password") String password) {
        //查询用户
        User loginUser = userServer.findByUserName(username);

        //判断用户是否存在
        if (loginUser == null) {
            return Result.error("用户名错误");
        }

        //判断密码是否正确
        if (!Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            return Result.error("密码错误");
        }

        //登录成功
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", loginUser.getId());
        claims.put("username", loginUser.getUsername());
        String token = JwtUtil.genToken(claims);
        //把token 存储到redis中
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.set(token,token,1, TimeUnit.HOURS);
        return Result.success(token);
    }

    /**
     * 获取用户详情信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //根据用户名查询用户
        /*Map<String, Object> userMap = JwtUtil.parseToken(token);

        String username = String.valueOf(userMap.get("username"));*/

        Map<String, Object> userMap = ThreadLocalUtil.get();

        String username = String.valueOf(userMap.get("username"));

        if (username == null) {
            return Result.error("解析token失败，请检查");
        }

        User user = userServer.findByUserName(username);

        return Result.success(user);

    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        //更新用户
        userServer.update(user);
        return Result.error("更新成功");
    }

    /**
     * 更新用户头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userServer.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, Object> params, @RequestHeader("Authorization") String token) {
        //获取请求参数并校验
        //原密码
        String old_pwd = String.valueOf(params.get("old_pwd"));
        //新密码
        String new_pwd = String.valueOf(params.get("new_pwd"));
        //确认新密码
        String re_pwd = String.valueOf(params.get("re_pwd"));

        if (!StringUtils.hasLength(old_pwd)) {
            return Result.error("原密码不能为空");
        }

        if (!StringUtils.hasLength(new_pwd)) {
            return Result.error("新密码不能为空");
        }

        if (!StringUtils.hasLength(re_pwd)) {
            return Result.error("确认新密码不能为空");
        }

        if (!new_pwd.equals(re_pwd)) {
            return Result.error("新密码与确认新密码不一致");
        }

        //校验原密码是否正确
        //获取当前用户密码
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = String.valueOf(map.get("username"));

        User loginUser = userServer.findByUserName(username);

        //原密码加密校验
        old_pwd = Md5Util.getMD5String(old_pwd);

        if (!loginUser.getPassword().equals(old_pwd)) {
            return Result.error("原密码错误，请重新输入");
        }

        //更新密码
        userServer.updatePwd(new_pwd);

        //删除redis中对应的token
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.getOperations().delete(token);


        return Result.success();
    }

}
